package com.example.waterfall.util;

import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.example.waterfall.BuildConfig;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;

/**
 * 处理图片的大小。解析。
 * 
 * @author huangrongcai
 * 
 */
public class ImageResizer extends ImageWorker {
	private static final String TAG = "ImageWorker";
	protected int mImageWidth = 100;
	protected int mImageHeight = 100;

	/**
	 * 构造时，可以指定图片宽高
	 * 
	 * @param context
	 * @param imageWidth
	 * @param imageHeight
	 */
	public ImageResizer(Context context, Handler handler, int imageWidth, int imageHeight) {
		super(context,handler);
		setImageSize(imageWidth, imageHeight);
	}

	/**
	 * 构造时，可以指定图片宽高,如果只设定边框，默认为宽=高
	 * 
	 * @param context
	 * @param imageSize
	 */
	public ImageResizer(Context context,Handler handler, int imageSize) {
		super(context,handler);
		setImageSize(imageSize);
	}

	public ImageResizer(Context context,Handler handler) {
		super(context,handler);
	}

	/**
	 * 设置宽高
	 * 
	 * @param width
	 * @param height
	 */
	public void setImageSize(int width, int height) {
		mImageWidth = width;
		mImageHeight = height;
	}

	public void setImageSize(int size) {
		setImageSize(size, size);
	}

	private Bitmap processBitmap(int resId) {
		if (BuildConfig.DEBUG) {
			Log.d(TAG, "processBitmap - " + resId);
		}
		return decodeSampledBitmapFromResource(mContext.getResources(), resId,
				mImageWidth, mImageHeight);
	}

	@Override
	protected Bitmap processBitmap(Object data) {
		return processBitmap(Integer.parseInt(String.valueOf(data)));
		// return null;

	}

	public static Bitmap decodeSampledBitmapFromResource(Resources res,
			int resId, int reqWidth, int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(res, resId, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeResource(res, resId, options);
	}

	/**
	 * 图片压缩采样
	 * @param filename
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static synchronized Bitmap decodeSampledBitmapFromFile(
			String filename, int reqWidth, int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filename, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filename, options);
		// 改进方法，避免decoder error;
		// byte[] bytes = filename.getBytes();
		// return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
		// options);
	}

	/**
	 * 解码图片，资源来自输入流。
	 * 
	 * @param inStream
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static synchronized Bitmap decodeSampledBitmapFromStream(
			InputStream inStream, int reqWidth, int reqHeight) {

		// 先将流资源获取到本内存，不必要比流中多次获取，提高效用
		byte[] data = getBytesFromInputStream(inStream);
		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeByteArray(data, 0, data.length, options);
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
Log.i(TAG, ""+inSampleSize);
			// This offers some additional logic in case the image has a strange
			// aspect ratio. For example, a panorama may have a much larger
			// width than height. In these cases the total pixels might still
			// end up being too large to fit comfortably in memory, so we should
			// be more aggressive with sample down the image (=larger
			// inSampleSize).

			final float totalPixels = width * height;

			// Anything more than 2x the requested pixels we'll sample down
			// further.
			final float totalReqPixelsCap = reqWidth * reqHeight * 2;

			while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
				inSampleSize++;
			}
		}
		return inSampleSize;
	}

	/**
	 * 适配屏幕 尺寸=屏/列数<br>
	 * 获取最住尺寸适配手机屏幕 <br>
	 * 计算： 已知屏宽，图片实际宽高 求，按比屏比例缩小后的宽高 高=（屏宽*高）/宽
	 * 
	 * @param colums
	 *            列数
	 */
	public void setFitScreen(int colums) {
		WindowManager wm = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		int screenWidth = wm.getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
		int screenHeight = wm.getDefaultDisplay().getHeight(); // 屏幕高（像素，如：800p）
		Log.i(TAG, "前" + mImageWidth + ":" + mImageHeight);
		int w = 0;
		int h = 0;
		float rate;

		// (90/3)*400/300
		w = screenWidth / colums;
		// h = w * mImageHeight / mImageWidth;
		h = Math.round((float) mImageHeight * (float) w / (float) mImageWidth);
		mImageWidth = w;
		mImageHeight = h;

		// 高=（屏宽*高）/宽

		Log.i(TAG, "后" + mImageWidth + ":" + mImageHeight);
	}

	/**
	 * 设置缩放比<br>
	 * <1缩小<br>
	 * =1原大<br>
	 * >放大<br>
	 * 
	 * @param rate
	 *            分数
	 * 
	 */
	// public void setScale(float rate){
	//
	// }

	/**
	 * 输入Stream转为字节数组备用
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] getBytesFromInputStream(InputStream is) {
		ByteArrayOutputStream outstream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024]; // 用数据装
		int len = -1;
		try {
			while ((len = is.read(buffer)) != -1) {
				outstream.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				outstream.close();

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Log.i(TAG, "长度" + outstream.toByteArray().length);
		return outstream.toByteArray();
	}
}
